package com.zy.xuanwo.acitivity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zy.xuanwo.R;
import com.zy.xuanwo.application.MyApplication;
import com.zy.xuanwo.utils.RegexUtils;
import com.zy.xuanwo.utils.SharedPreferencesUtils;
import com.zy.xuanwo.utils.ToastUtils;
import com.zy.xuanwo.utils.URLConstants;
import com.zy.xuanwo.utils.UserInfoSPManager;
import com.zy.xuanwo.utils.WeakHandler;
import com.zy.xuanwo.view.CleanEditText;
import com.zy.xuanwo.view.CustomToast;
import com.zy.xuanwo.zyc.portal.bean.ErrorMessag;
import com.zy.xuanwo.zyc.portal.bean.LoginToken;
import com.zy.xuanwo.zyc.portal.callback.GetCommonResultListener;
import com.zy.xuanwo.zyc.portal.callback.LoginListener;
import com.zy.xuanwo.zyc.portal.service.imp.PortalMagger;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by njb on 2016/7/3.
 */
public class LoginActivity extends AppCompatActivity implements View.OnClickListener ,CompoundButton.OnCheckedChangeListener {


    @Bind(R.id.left_sliding_menu_iv)
    ImageView leftSlidingmenuIv;
    @Bind(R.id.edit_account_number)
    CleanEditText editAccountNumber;
    @Bind(R.id.edit_current_password)
    CleanEditText editCurrentPassword;
    @Bind(R.id.btn_login)
    Button btnLogin;
    @Bind(R.id.forget_password_tv)
    TextView forgetPasswordTv;
    @Bind(R.id.register_tv)
    TextView registerTv;
    @Bind(R.id.remember_password)
    CheckBox rememberPassword;
    @Bind(R.id.auto_login)
    CheckBox autoLogin;

    private String userName;
    private boolean isAutoLogin = true;
    private AlertDialog mAlertDialog;
    private String userToken;

    public static final int REGISTER_SUCCESS = 0x01;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        initView();

        if (getIntent().getFlags() == ForgetPassWordActivity.RESET_PASSWORD_SUCCESS || getIntent().getFlags() == UpdatePasswordActivity.UPDATE_PASSWORD_SUCCESS) {
            editAccountNumber.setText(UserInfoSPManager.getUserName());
            editCurrentPassword.requestFocus();
        } else {
            prepareForLogin();
        }
    }

    private void initView() {
        if (SharedPreferencesUtils.UNCHECKED.equals(SharedPreferencesUtils.get(this, SharedPreferencesUtils.REMEMBER_PASSWORD, SharedPreferencesUtils.CHECKED))) {
            rememberPassword.setChecked(false);
        }

        if (SharedPreferencesUtils.UNCHECKED.equals(SharedPreferencesUtils.get(this, SharedPreferencesUtils.AUTO_LOGIN, SharedPreferencesUtils.CHECKED))) {
            autoLogin .setChecked(false);
        }
    }

    private void prepareForLogin() {
        editAccountNumber.setText(UserInfoSPManager.getUserName());
        if (rememberPassword.isChecked()) {
            editCurrentPassword.setText(UserInfoSPManager.getPassword());
        } else {
            return;
        }
        if (editAccountNumber.getText().toString().trim().equals("")) {
            editAccountNumber.requestFocus();
        } else if (editCurrentPassword.getText().toString().trim().equals("")) {
            editCurrentPassword.requestFocus();
        } else {
            if (autoLogin.isChecked()) {
                showAlertDialog();
                doLoginRequest();
            }
        }
    }

    private void doLoginRequest() {
        userName = editAccountNumber.getText().toString().trim();
        final String password = editCurrentPassword.getText().toString().trim();

        if (checkInput(userName, password)) {
            OkHttpUtils.post()
                    .url(URLConstants.LOGING_URL)
                    .addHeader("token", "446f8fd7-8fc3-426d-8c70-283c021dd380")
                    .addHeader("X-Request-Sign", "f033abaf9eac94ffc03d25ee6be445e3, 1467598209")
                    .addHeader("X-Application-Id", "3d632345-abd5-4c7c-b157-6d12cd3f0dde")
                    .addParams("username", userName)
                    .addParams("password", password)
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            Log.e("login",e+"");
                            ToastUtils.showShort("登录失败,用户名或密码错误");
                        }

                        @Override
                        public void onResponse(final String response, int id) {
                            Log.e("login",response+"");

                            new WeakHandler()
                                    .postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            if(mAlertDialog !=null && mAlertDialog.isShowing())
                                            mAlertDialog.dismiss();
                                            if (isAutoLogin) {
                                                LoginToken loginToken = new Gson().fromJson(response, LoginToken.class);
                                                UserInfoSPManager.saveUserInfo(loginToken, userName, password);
                                                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                                                ToastUtils.showShort("登录成功");
                                                LoginActivity.this.finish();
                                            }
                                        }
                                    },2000 );

                        }
                    });
        }
    }

    private boolean checkInput(String userName, String password) {
        if (TextUtils.isEmpty(userName)) {
            ToastUtils.showShort("帐号不能为空");
        } else if (TextUtils.isEmpty(password)) {
            ToastUtils.showShort("密码不能为空");
        } else {
            if (!(RegexUtils.checkMobile(userName) || RegexUtils.checkEmail(userName))) {
                ToastUtils.showShort("手机号或邮箱格式不正确");
            } else {
                return true;
            }
        }
        return false;
    }

    @OnClick({R.id.left_sliding_menu_iv, R.id.btn_login, R.id.forget_password_tv, R.id.register_tv})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.left_sliding_menu_iv:
                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                break;
            case R.id.btn_login:
                isAutoLogin = true;
                doLoginRequest();
                break;
            case R.id.forget_password_tv:
                startActivity(new Intent(LoginActivity.this, ForgetPassWordActivity.class));
                break;
            case R.id.register_tv:
                startActivityForResult(new Intent(LoginActivity.this, RegisterActivity.class),REGISTER_SUCCESS);
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REGISTER_SUCCESS && resultCode == RESULT_OK) {
            editAccountNumber.setText(data.getExtras().getString("account"));
            editCurrentPassword.requestFocus();
            ToastUtils.showShort("注册成功，请登录");
        }
    }

    @OnCheckedChanged({R.id.remember_password, R.id.auto_login})
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.remember_password :
                if (!isChecked) {
                    UserInfoSPManager.removePassword();
                    SharedPreferencesUtils.put(this,SharedPreferencesUtils.REMEMBER_PASSWORD,SharedPreferencesUtils.UNCHECKED);
                } else {
                    SharedPreferencesUtils.put(this,SharedPreferencesUtils.REMEMBER_PASSWORD,SharedPreferencesUtils.CHECKED);
                }
                break;

            case R.id.auto_login :
                if (!isChecked) {
                    SharedPreferencesUtils.put(this,SharedPreferencesUtils.AUTO_LOGIN,SharedPreferencesUtils.UNCHECKED);
                } else {
                    SharedPreferencesUtils.put(this,SharedPreferencesUtils.AUTO_LOGIN,SharedPreferencesUtils.CHECKED);
                }
                break;
        }
    }

    private void showAlertDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        mAlertDialog = builder.show();
        builder.setTitle("自动登录");
        builder.setMessage("正在自动登录...");
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                isAutoLogin = false;
            }
        });
        builder.show();
    }
}